﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using Helper;
using System.IO;

public partial class Reports_RedBalLoansDetailProjectionReport : System.Web.UI.Page
{    
    static LoanBLL businessObject;
    static int pageIndex;
    static int pageSize;
    static DateTime fromReportDate;
    static DateTime toReportDate;
        
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false) /*first load*/
        {
            try
            {
                Common.AppendPageTitle(Master, Globals.MasterPageHeaderID, " - Reducing Balance Detailed Projected Interest");

                businessObject = new LoanBLL();
                /*set properties default values for gridview pager*/
                txtFromReportDate.Value = DateTime.Now.AddMonths(-2).ToString("dd-MM-yyyy");
                txtToReportDate.Value = DateTime.Now.AddMonths(-1).ToString("dd-MM-yyyy");
                pageIndex = 1;
                pageSize = Int32.Parse(ddlPageSize.SelectedValue.ToString());
            }
            catch (Exception ex)
            {
                HandleStandardException(ex);
            }
        }        
    }
    protected void btnRunReport_Click(object sender, EventArgs e)
    {        
        try
        {
            pageIndex = 1;//reset page index to the first page
            fromReportDate = DateTime.ParseExact(txtFromReportDate.Value.ToString(), "dd-MM-yyyy", CultureInfo.InvariantCulture);
            toReportDate = DateTime.ParseExact(txtToReportDate.Value.ToString(), "dd-MM-yyyy", CultureInfo.InvariantCulture);
            
            /*check if report date (from) is less than (to)*/
            if ((fromReportDate.Year == toReportDate.Year && fromReportDate.Month <= toReportDate.Month) || fromReportDate <= toReportDate)
            {
                BindGridView();
                DisplayErrorMessage(String.Empty, display: false);
            }
            else
            {
                UnBoundGridView();//remove previous data set and hide gridview
                DisplayErrorMessage("Invalid report date<br />Please review dates and try again");
            }
        }
        catch (FormatException ex)
        {
            DisplayErrorMessage("Invalid date format. Please review date and try again");
        }
        catch (Exception ex)
        {
            HandleStandardException(ex);
        }
    }

    protected void btnPevious_Click(object sender, EventArgs e)
    {
        if (pageIndex > 1)
            pageIndex--;
        try
        {
            BindGridView();
        }
        catch (Exception ex)
        {
            HandleStandardException(ex);
        }
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        if (pageIndex < 100)
            pageIndex++;
        try
        {
            BindGridView();
        }
        catch (Exception ex)
        {
            HandleStandardException(ex);
        }
    }
    protected void btnGotoPage_Click(object sender, EventArgs e)
    {
        try
        {
            pageIndex = Int32.Parse(txtCurrentPage.Text);
            BindGridView();
        }
        catch (Exception ex)
        {
            HandleStandardException(ex);
        }
    }

    protected void gvDetailedReport_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                cell.Style["border-bottom"] = "4px solid #666666";
                cell.Style["padding"] = "7px";
                cell.Wrap = false; 
                if (cell.Text == "RowNum") 
                    cell.Text = "#";            
            }
        }
        else if (e.Row.RowType == DataControlRowType.DataRow)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                cell.Wrap = false;
            }
        }
    }

    protected void gvDetailedReport_DataBound(object sender, EventArgs e)
    {
        try
        {
            int totalRecords = businessObject.GetRedBalLoansDetailedInterestProjectionCount(fromReportDate, toReportDate);
            int totalPages = Convert.ToInt32(Math.Ceiling((double)totalRecords / pageSize));
            txtTotalPages.Text = totalPages.ToString();

            txtCurrentPage.Text = pageIndex.ToString();
            if (pageIndex == 1)
                btnPevious.Enabled = false;
            else
                btnPevious.Enabled = true;

            if (pageIndex == totalPages)
                btnNext.Enabled = false;
            else
                btnNext.Enabled = true;
            detailedReportContainer.Style.Add("display", "block");
            rvPageIndex.MaximumValue = (totalPages > 0) ? totalPages.ToString() : "1";
        }
        catch (Exception ex)
        {
            HandleStandardException(ex);
        }
    }

    protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            pageIndex = 1;
            pageSize = Int32.Parse(ddlPageSize.SelectedValue.ToString());
            BindGridView();
        }
        catch (Exception ex)
        {
            HandleStandardException(ex);
        }

    }

    private void BindGridView()
    {
        gvDetailedReport.DataSource = businessObject.GetRedBalLoansDetailedInterestProjection(
            fromReportDate,
            toReportDate,
            pageIndex,
            pageSize);
        gvDetailedReport.DataBind();
    }

    private void UnBoundGridView()
    {
        gvDetailedReport.DataSource = null;
        gvDetailedReport.DataBind();
        detailedReportContainer.Style.Add("display", "none");
    }

    private void DisplayErrorMessage(string errorMessage, bool display = true)
    {
        if (display == true)
        {
            this.errorMessage.InnerHtml = errorMessage;
            this.errorMessage.Visible = true;
        }
        else
            this.errorMessage.Visible = false;
    }

    private void HandleStandardException(Exception ex)
    {
        Error exception = new Error(ex.GetType().ToString(), ex.Message, DateTime.Now, stackTrace: ex.StackTrace, additionalDetails: ex.Source);
        ErrorLogBLL exceptionUtility = new ErrorLogBLL();
        int logId = exceptionUtility.LogException(exception);

        DisplayErrorMessage(
            "An error occurred in the application.<br />" +
            "The error has been logged to the system with logId:" + logId + ".<br />" +
            "Please notify the site administrator for assistance."
            );
    }
    protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        try
        {
            /*store page size */
            int initialPageSize = pageSize;
            /*set values to 0 to bypass paging*/
            pageIndex = 0;
            pageSize = 0;
            /*temporarily bind gridview to export non-paged content to excel*/
            BindGridView();

            /*set up the response properties*/
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=Reducing Balance Loans Detailed Report.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
            gvDetailedReport.RenderControl(textWriter);
            Response.Write(stringWriter.ToString());
            /*restore paging and bind gridview to paged data*/
            pageIndex = 1;
            pageSize = initialPageSize;
            BindGridView();
            Response.End();
        }
        catch (Exception ex)
        {
            HandleStandardException(ex);
        }
    }

    public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
    {
        //by pass verification for Server Form
    }   
}